<template xmlns="http://www.w3.org/1999/html">
  <div class="app-container">

    <el-row :gutter="10" class="mb8" type="flex" align="middle">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:tripsApply:add']"
        >申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:tripsApply:edit']"
        >修改</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['system:tripsApply:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:tripsApply:export']"
        >导出</el-button>
      </el-col>


      <!-- 综合搜索框 -->
      <el-col :span="14" >
        <el-input
          v-model="comprehensiveQueryParams.inputValue"
          placeholder="请输入出差目的地或审批状态(待定/通过/驳回)"
          clearable
          @keyup.enter.native="handleComprehensiveQuery(comprehensiveQueryParams.inputValue)"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleComprehensiveQuery(comprehensiveQueryParams.inputValue)"
          ></el-button>
        </el-input>
      </el-col>

      <!-- 右侧刷新工具栏 -->
      <el-col :span="1.5" style="margin-left: auto">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-col>
    </el-row>


    <el-table v-loading="loading" :data="tripsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请人姓名" align="center" prop="nickName"></el-table-column>
      <!--      <el-table-column label="申请ID" align="center" prop="id" />-->
      <!--      <el-table-column label="用户ID" align="center" prop="userId" />-->
      <!--      <el-table-column label="审批人ID" align="center" prop="approverId" />-->
      <el-table-column label="出差目的地" align="center" prop="destination" />
      <el-table-column label="出差开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出差结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出差目的" align="center" prop="purpose" />
      <el-table-column label="审批状态" align="center" prop="status" width="180">
        <template v-slot="scope">
          <el-tag :type="getStatusType(scope.row.status)"
                  @click="selectResult(scope.row.id)"
                  v-hasPermi="['system:tripsApply:result']">
            {{ setStatusToChinese(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="approvalTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:tripsApply:edit']"
          >修改</el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['system:tripsApply:remove']"-->
          <!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出差申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" disabled/>
        </el-form-item>
        <el-form-item label="审批人ID" prop="approverId">
          <el-input v-model="form.approverId" disabled/>
        </el-form-item>
        <el-form-item label="出差目的地" prop="destination">
          <el-input v-model="form.destination" placeholder="请输入出差目的地" />
        </el-form-item>
        <el-form-item label="出差开始日期" prop="startDate">
          <el-date-picker clearable
                          v-model="form.startDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出差开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出差结束日期" prop="endDate">
          <el-date-picker clearable
                          v-model="form.endDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出差结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出差目的" prop="purpose">
          <el-input v-model="form.purpose" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--展示审批原因对话框-->
    <el-dialog :title="title"  :visible.sync="openResultDialog" width="300px" append-to-body>
      <template slot-scope="scope">
        <span>{{(form.result)}}</span>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openResultDialog = false">取 消</el-button>
        <el-button type="primary" @click="openResultDialog = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTrips,
  delTrips,
  addTrips,
  updateTrips,
  selectApplyResult,
  selectCurrentUserBusinessTripsById,
  selectDetailedBusinessTripsByIdAndInput
} from "@/api/system/trips";


export default {
  name: "Trips",

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出差申请表格数据
      tripsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openResultDialog: false,
      // 默认审批人为1
      defaultApproverId: 1,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        approverId: null,
        nickName: null,
        destination: null,
        startDate: null,
        endDate: null,
        purpose: null,
        status: null,
        approvalTime: null,
        createdTime: null,
        updatedTime: null
      },
      //综合搜索框内的数据对象
      comprehensiveQueryParams: {
        inputValue: '', // 搜索框输入值
        status: null,   // 状态
        destination: null // 目的地
      },
      //获取状态类型，用来更改颜色
      getStatusType(status) {
        switch (status) {
          case 'PENDING':
            return 'warning'; // 黄色
          case 'APPROVED':
            return 'success'; // 绿色
          case 'REJECTED':
            return 'danger'; // 红色
          default:
            return 'info'; // 默认灰色
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        destination: [
          { required: true, message: "出差目的地不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "出差开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "出差结束日期不能为空", trigger: "blur" }
        ],
        purpose: [
          { required: true, message: "出差目的不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.userId = this.$store.state.user.id;
    this.getList();
  },
  methods: {

    handleComprehensiveQuery(value) {
      this.queryParams.pageNum = 1;
      // 清空上次搜索条件
      this.comprehensiveQueryParams.status = null;
      this.comprehensiveQueryParams.destination = null;

      // 定义状态映射
      const statusMap = {
        "待定": "PENDING",
        "通过": "APPROVED",
        "驳回": "REJECTED"
      };
      // 如果是审批状态
      if (statusMap[value]) {
        this.comprehensiveQueryParams.status = statusMap[value];
        this.comprehensiveQueryParams.destination = null;
        console.log("status的字段为:",this.comprehensiveQueryParams.status);
      } else {
        this.comprehensiveQueryParams.destination = value; // 目的地
        this.comprehensiveQueryParams.status = null;
        console.log("destination的字段为：",this.comprehensiveQueryParams.destination);
      }
      // 调用搜索方法
      this.getDetailedList();
      this.comprehensiveQueryParams.inputValue = "";
    },
    /* 将后端status翻译为中文 */
    setStatusToChinese(status) {
      switch (status) {
        case 'PENDING':
          return '待定';
        case 'APPROVED':
          return '通过';
        case 'REJECTED':
          return '驳回';
      }
    },
    /** 查询出差申请列表 */
    getList() {
      this.loading = true;
      const currentUserId = this.userId;
      selectCurrentUserBusinessTripsById(currentUserId).then(response => {
        this.tripsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //综合搜索框根据用户id和所输入的内容来搜索出差申请记录
    getDetailedList() {
      this.loading = true;
      //设置搜索参数变量
      const params = {
        id: this.userId,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        status: this.comprehensiveQueryParams.status,
        destination: this.comprehensiveQueryParams.destination
      };
      console.log("传递给后端的status值为：", params.status);
      console.log("传递给后端的destination值为：", params.destination);
      selectDetailedBusinessTripsByIdAndInput(params).then(response => {
        this.tripsList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$modal.msgError("查询失败");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        approverId: null,
        destination: null,
        startDate: null,
        endDate: null,
        purpose: null,
        status: null,
        result: null,
        approvalTime: null,
        createdTime: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.userId = this.userId;
      this.form.approverId = this.defaultApproverId;
      this.open = true;
      this.title = "添加出差申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTrips(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改出差申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTrips(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.userId = this.userId;
            addTrips(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作  */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除出差申请编号为"' + ids + '"的数据项？').then(function() {
        return delTrips(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/trips/export', {
        ...this.queryParams
      }, `trips_${new Date().getTime()}.xlsx`)
    },
    /*查询审批原因按钮操作*/
    selectResult(id) {
      console.log(id);
      if (!id) {
        this.$modal.msgError("未获取到审批ID");
        return;
      }
      selectApplyResult(id).then(response => {
        if (response.data) {
          this.form.result = response.data.result; // 确保正确赋值
          this.title = "审批结果";
          this.openResultDialog = true; // 打开对话框
        } else {
          this.$modal.msgError("未获取到审批结果");
        }
      }).catch(() => {
        this.$modal.msgError("查询审批结果失败");
      });
    }

  }
};
</script>


<style scoped>
.mb8 {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.el-input {
  width: 100%;
}

/* 只针对工具栏按钮的样式 */
.mb8 .el-button {
  width: 100%;
}

/* 确保弹框底部按钮水平排列 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 弹框底部按钮样式重置 */
.dialog-footer .el-button {
  width: auto;
}
</style>
